<?php

namespace App\Http\Controllers\Foundation;

use App\Events\Event;
use App\Model\Business\Classe;
use App\Model\Business\ClasseStuden;
use App\Model\Business\ScheduleStuden;
use App\Model\Eeoapi\Eeosync;
use App\Model\Foundation\Student;
use App\Model\Foundation\StudentRemark;
use App\Model\System\NoticeConfig;
use App\Model\System\SystemConfig;
use App\Model\System\Token;
use App\Model\System\User;
use App\Events\TeacherEvent;
use App\Model\Business\Schedule;
use App\Model\Foundation\CourseType;
use App\Model\Foundation\TeacherCourseType;
use App\Model\Foundation\TeacherEducation;
use App\Model\Foundation\TeacherExperience;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;

use App\Model\Foundation\Teacher;
use App\Http\Controllers\MessagePacket;


class TeacherController extends BaseController
{
    use MessagePacket;


    function  __construct(){}


    /**
     * 获取单一教师的信息
     * @param $id
     * @return packetMessage
     */
    function getTeacher($id)
    {
        $id = intval($id);
        $teacher = Teacher::find($id);
        $account = User::where('userid',$teacher->userid)->pluck('account')->first();
        $teacher->coursedesc = TeacherCourseType::getCourseTypeIds($id);
        $teacher->account = $account;
        $teacher->educations = $teacher->educations;
        $teacher->experiences = $teacher->experiences;
        if(empty($teacher)){
            return $this->fail($teacher, '数据不存在');
        }
        return $this->success($teacher);
    }


    /**
     * 批量查询教师列表
     * @param Request $request
     * @return packetMessage
     */
    function getTeachers(Request $request)
    {
        if($request->has('perPage')){
            $limit = $request->get('perPage');
        }

        $query = Teacher::wherenotNull('teacheruid');

        if($request->has('lastname')) {
            $lastname = $request->get('lastname');
            $query->where('lastname', 'like', "%$lastname%");
        }
        if($request->has('status')) {
            $status = $request->get('status');
            $query->where('status', $status);
        }
        if($request->has('mobile')) {
            $mobile = $request->get('mobile');
            $query ->orwhere('mobile', 'like', "%{$mobile}%");
        }
        if($request->has('ClassInNo')) {
            $ClassInNo = $request->get('ClassInNo');
            $query ->orwhere('ClassInNo', 'like', "%{$ClassInNo}%");
        }



        # 需要／不需要 分页
        if($request->has('page')){
            $infos = $query->paginate($limit);
            $teachers = $infos->items();
        }else{
            $teachers = $query->get();
        }

        # 关联
        foreach ($teachers as $key => $teacher) {
            $id = $teacher->teacheruid;
            $teacher->coursedesc = TeacherCourseType::getCourseTypeIds($id);
            if($teacher->coursedesc){
                $teacher->coursedesc = CourseType::getCourseTypes($teacher->coursedesc);
          }
          $teachers[$key] = $teacher;
        }

        # 需要／不需要 分页
        if($request->has('page')){
            $infos = $infos->toArray();
            unset($infos['data']);
            $data['list'] = $teachers;
            $data['pager'] = $infos;
        }else{
            $data = $teachers;
        }

        if(empty($teachers)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }

    /**
     * 根据课程类型获取教师列表
     * @param Request $request,$id:coursetypeId
     * @return packetMessage
     */
    function getTeachersByCourseType(Request $request,$id=0)
    {
        $id = intval($id);
        $teacherIds = TeacherCourseType::getTeacherIds($id);
        $query = Teacher::whereIn('teacheruid',$teacherIds);

        if($request->has('status')) {
            $status = $request->get('status');
            $query->where('status', $status);
        }

        # 需要／不需要 分页
        if($request->has('page')) {
            $limit = 30;
            if ($request->has('perPage')) {
                $limit = $request->get('perPage');
            }
            $infos = $query->paginate($limit);
            $teachers = $infos->items();
        }else{
            $teachers = $query->get();
        }
        # 关联
        foreach ($teachers as $key => $teacher) {
            $id = $teacher->teacheruid;
            $teacher->coursedesc = TeacherCourseType::getCourseTypeIds($id);
            if($teacher->coursedesc){
                $teacher->coursedesc = CourseType::getCourseTypes($teacher->coursedesc);
            }
            $teachers[$key] = $teacher;
        }
        # 需要／不需要 分页
        if($request->has('page')) {
            $infos = $infos->toArray();
            unset($infos['data']);
            $data['list'] = $teachers;
            $data['pager'] = $infos;
        }else{
            $data = $teachers;
        }
        # 返回
        if(empty($data)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }


    /**
     * 添加一个教师
     * @param Request $request
     * @return packetMessage
     */
    function  addTeacher(Request $request)
    {
        try {
            $fields = $request->all();

            # 排重 依照ClassInNo
            $oldteacher = Teacher::where('ClassInNo', $fields['ClassInNo'])->first();
            if ($oldteacher) {
                return $this->fail(false, '教师ClassIn 账号已经存在.');
            }
            # 教师表电话号排重
            $teacher = Teacher::where('mobile', $fields['mobile'])->first();
            if($teacher){
                return $this->fail(false,'手机号已存在');
            }

            # 创建
            $teacher = new Teacher($fields);
            $teacher->save();

            # 注册教师到EEO
            $password = '';
            if ($request->has('password')) $password = $request->get('password');
            $this->dispatchEvent($teacher, Event::CREATE, $password);

            # educations
            if ($request->has('educations')) {
                $edus = [];
                $educations = $request->educations;
                foreach ($educations as $key => $edu) {
                    $edus[] = new TeacherEducation($edu);
                }
            }
            # experiences
            if ($request->has('experiences')) {
                $exps = [];
                $experiences = $request->experiences;
                foreach ($experiences as $key => $exp) {
                    $exps[] = new TeacherExperience($exp);
                }
            }
            # 关联用户表
            $user = User::where('number',$fields['mobile'])->first();
            if(empty($user)) {
                $obj = new User();
                $obj->userid = User::generateID();
                $obj->type = User::TEACHER;
                $obj->email = $fields['email'];
                $obj->number = $fields['mobile'];
                $obj->islock = User::UNLOCK;
                $password = '123456';
                $config = SystemConfig::find(1);
                if($config){
                    $password = $config->defaultpassword;
                }
                $obj->setSecurityCode($password);
                $obj->updateCreator();
                $teacher->userid = $obj->userid;
                $obj->save();
            }
            else {
                $teacher->userid = $user->userid;
            }
            #保存成功
//            $teacher->created_by = Token::user()->userid;
            $teacher->save();

            #新建提醒  默认开启微信及邮件通知，课前60分钟提醒，每天12点提醒。
            $obj = new NoticeConfig([
                'utype'=>1,
                'uid'=>$teacher->teacheruid,
                'ntype'=>1,
                'byemail'=>1,
                'bywechat'=>1,
                'ahead'=>60,
                'perday'=>12]);
            $obj->save();
            $obj2 = new NoticeConfig(['utype'=>1, 'uid'=>$teacher->teacheruid, 'ntype'=>2]);
            $obj2->save();

            #更新教师_课程类型表
            if (!empty($fields['coursedesc'])) {
                $teacherid = $teacher->teacheruid;
                foreach ($fields['coursedesc'] as $typeId) {
                    $courses= new TeacherCourseType(
                        ['teacheruid' => $teacherid,
                        'coursetypeid' => $typeId]);
                    $courses->save();
                }
            }

            if (isset($edus)) $teacher->educations()->saveMany($edus);
            if (isset($exps)) $teacher->experiences()->saveMany($exps);

            return $this->success($teacher);
        }catch (\Exception $e){
            if($teacher) $teacher->delete();
            return $this->fail(false, '添加失败: '.$e->getMessage());
        }
    }


    /**
     * 更新某个教师的信息
     * @param Request $request
     * @return packetMessage
     */
    function  updateTeacher(Request $request, $id)
    {
        try{
            $teacherid = $id;
            if($request->has('teacheruid')){
                $teacherid = $request->teacheruid;
            }
            if(empty($teacherid)){
                return $this->fail(null,'缺少教师id');
            }

            $teacher = Teacher::find($teacherid);
            #
            $educations = [];
            $fields = $request->all();
            if($request->has('educations')){
                $educations = $fields['educations']; unset($fields['educations']);
            }

            $experiences = [];
            if($request->has('experiences')){
                $experiences = $fields['experiences']; unset($fields['experiences']);
            }

            foreach($fields as $key=>$val){
                if($key != 'coursedesc')
                    $teacher->$key = $val;
            }
            if($request->has('lastname') && $request->has('photo')){
                $this->dispatchEvent($teacher, Event::UPDATE);
            }
            if($request->has('mobile')){
                #修改手机号，如果手机号不存在，则更新用户表。
                if(!User::updateMobile($request, $teacher)){
                    return $this->fail(false,'手机号已经存在，不能更改.');
                }
            }

            #更新教师课程类型
            if($request->has('coursedesc')) {
                TeacherCourseType::where('teacheruid',$teacherid)->delete();
                $courseTypeIds= $fields['coursedesc'];
                foreach ($courseTypeIds as $typeId){
                    $courses= new TeacherCourseType();
                    $courses->teacheruid = $teacherid;
                    $courses->coursetypeid = $typeId;
                    $courses->save();
                }
            }
            else{
                TeacherCourseType::where('teacheruid',$teacherid)->delete();
            }

            #更新教师教育经历
            if($educations){
                TeacherEducation::where('teacheruid', $teacherid)->delete();
                $edus = $educations;
                foreach ($edus as $edu){
                    $te = new TeacherEducation($edu);
                    $teacher->educations()->save($te);
                }
            }

            #更新教师工作经验
            if($experiences){
                TeacherExperience::where('teacheruid', $teacherid)->delete();
                $exps = $experiences;
                foreach ($exps as $exp){
                    $tex = new TeacherExperience($exp);
                    $teacher->experiences()->save($tex);
                }
            }

//            #更新人
//            $teacher->updated_by = Token::user()->userid;

            if($teacher->save()){

                return $this->success($teacher);
            }else{
                return $this->fail(null,'保存失败');
            }
        }catch (\Exception $e){
            return $this->fail(false,'保存失败,'.$e->getMessage());
        }

    }


    /**
     * 删除某个教师
     * @param $id
     * @return array
     * @throws \Exception
     */
    function  deleteTeacher($id)
    {
        $schedules = Schedule::where('teacheruid', $id)->first();
        if($schedules){
            return $this->fail(false, '请先删除教师排课，约课，班课后，再来删除教师');
        }
        try{
            TeacherEducation::where('teacheruid', $id)->delete();
            TeacherExperience::where('teacheruid', $id)->delete();
            TeacherCourseType::where('teacheruid',$id)->delete();
            Teacher::destroy($id);
            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false,'删除失败:'.$e->getMessage());
        }
    }

    /**
     * 删除教师简历
     * @param $id
     * @return array
     */
    function deleteTeacherResume($id)
    {
        $teacher = Teacher::find($id);
        $teacher->resume = '';
        $teacher->save();
        return $this->success(true);
    }


    /**
     * 抛出事件
     * @param $action
     * @param $teacher
     * @return mixed
     * @throws \Exception
     */
    protected function dispatchEvent($teacher, $action, $password=null)
    {
        try{
            $event = new TeacherEvent($action, $teacher, $password);
            event($event);
        }catch (\Exception $e){
            throw $e;
            return $e->getMessage();
        }
    }

    /**
     * 关联用户id
     * @param Request $request
     * @param $id
     * @return array
     */
    function associate(Request $request, $id)
    {
        if(!$request->has('userid')){
            return $this->fail(false, '参数不全');
        }

        $obj = Teacher::find($id);
        $obj->userid = $request->userid;
        if($obj->save()){
            return $this->success(true);
        }
        return $this->fail(false, '关联失败');
    }

    /**
     * 根据userid获取教师信息
     * @param $id：userid
     * @return array
     */
    function getTeacherByUserid($id)
    {
        $userid = intval($id);
        $teacheruid = Teacher::where('userid',$userid)->value('teacheruid');
        $teacher = Teacher::find($teacheruid);
        $teacher->coursedesc = TeacherCourseType::getCourseTypeIds($teacheruid);
        $teacher->educations = $teacher->educations;
        $teacher->experiences = $teacher->experiences;
        if(empty($teacher)){
            return $this->fail($teacher, '数据不存在');
        }
        return $this->success($teacher);
    }

    /**
     * 获取某个教师的所有班课
     * @param Request $request
     * @param $id:教师id
     * @return array
     */
    public function getMyClasses(Request $request, $id)
    {
        if($request->has('classname')){
            $classname = $request->get('classname');
        }
        if($request->has('studentname')){
            $studentname = $request->get('studentname');
        }
        if($request->has('perPage')){
            $limit = $request->get('perPage');
        }
        $classeids = Schedule::where('type',Schedule::LESSON)
            ->where('teacheruid',$id)
            ->pluck('classeid')->toArray();

        $search = '';

        if(isset($classname) && isset($studentname) ){
            $searchStudent = [];
            $searchClass = Classe::where('classname','like',"%$classname%")->pluck('classuid')->toArray();
            $studentids = Student::where('name','like',"%$studentname%")->pluck('studentuid')->toArray();
            if(!empty($studentids)){
                $searchStudent = ClasseStuden::whereIn('studentuid',$studentids)->pluck('classeid')->toArray();
            }
            $search = array_unique(array_merge($searchStudent,$searchClass));
        }

        //获取classeids的交集
        if($search != ''){
            $classeids = array_intersect($classeids,$search);
        }
//        if(empty($classeids)){
//            return $this->fail(false, '数据不存在');
//        }

        $query = DB::table('classes')->whereIn('classuid', $classeids);

        # 需要／不需要 分页
        if($request->has('page')) {
            $limit = 30;
            if($request->has('perPage')){
                $limit = $request->get('perPage');
            }
            $info = $query->paginate($limit);
            $classes = $info->items();
        }else{
            $classes = $query->get();
        }
        # 关联
        foreach ($classes as $class){
            $classid = $class->classuid;
            $class->studentcount = DB::table('classes_students')
                ->where('classeid',$classid)
                ->count();
            $class->last = DB::table('schedules')
                ->where('classeid',$classid)
                ->where('begintime','<','now()')
                ->orderBy('begintime','desc')->limit(1)->value('begintime');
            $class->finished = DB::table('schedules')
                ->where('classeid',$classid)
                ->where('begintime','<','now()')
                ->count();
            $class->total = DB::table('schedules')
                ->where('classeid',$classid)
                ->count();
        }

        # 需要／不需要 分页
        if($request->has('page')) {
            $info = $info->toArray();
            $data['list'] = $classes;
            unset($info['data']);
            $data['pager'] = $info;
        }else{
            $data = $classes;
        }

        if(empty($classes)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }

    /**
     * 获取我的学生所有课节
     * @param Request $request
     * @param $id:学生id
     * @return array
     */
    public function getMyStudentSchedules($id){
        $classinNo = Student::where('studentuid',$id)->value('ClassInNo');
        $scheduleids = ScheduleStuden::where('studentuid', $id)->pluck('scheduleid')->toarray();
        $query = Schedule::whereIn('scheduleid', $scheduleids);
        $schedules =$query->orderby('begintime','desc')->get();
        foreach ($schedules as $k=>$item){
            $begin = date('H:i', strtotime($item->begintime));
            $end = date('H:i', strtotime($item->endtime));
            $schedules[$k]->period = "$begin - $end";
            $schedules[$k]->eeosync = Eeosync::where('scheduleid',$item->scheduleid)
                ->where('type',Eeosync::STUDENT)
                ->where('userid',$classinNo)->first();
        }
        return $this->success($schedules);
    }

    /**
     * 我的学生:某个班课学生列表
     * @param Request $request
     * @param $id:学生id
     * @return array
     */
    public function getMyClassStudents(Request $request,$classeid){

        $id = $classeid;
        $identity = ClasseStuden::STUENDT;
        if($request->has('classeid')){
            $sid = $request->classeid;
        }
        if($request->has('identity')){
            $identity = $request->get('identity');
        }

        $studentids = ClasseStuden::where('classeid', $id)->where('identity', $identity)->get();
        if(!$studentids) {
            return $this->fail(false, '数据为空');
        }
        $ids = [];
        foreach ($studentids as $k=>$vals){
            $ids[] = $vals['studentuid'];
        }

        $query = Student::whereIn('studentuid',$ids)
            ->where(function($query)use($request){
                    if($request->has('name')){
                        $name = $request->name;
                        $query->where('name','like',"%$name%");
                    }
                    if($request->has('mobile')) {
                        $mobile = $request->mobile;
                        $query->orWhere('mobile', 'like', "%$mobile%");
                    }
                    if($request->has('ClassInNo')) {
                        $ClassInNo = $request->ClassInNo;
                        $query->orWhere('ClassInNo', 'like', "%$ClassInNo%");
                    }
            });

        # 需要／不需要 分页
        if($request->has('page')) {
            $limit = 30;
            if($request->has('perPage')){
                $limit = $request->get('perPage');
            }
            $info = $query->paginate($limit);
            $students = $info->items();
        }else{
            $students = $query->get();
        }

        foreach ($students as $student) {
            $last = Schedule::getStudentLastSchedule($student->studentuid);
            $student->last = $last;
            $student->hasRemark = false;
            $record = StudentRemark::where('studentid',$student->studentuid)->get()->toArray();
            if(!empty($record)) {
                $student->hasRemark = true;
            }
        }

        # 需要／不需要 分页
        if($request->has('page')) {
            $info = $info->toArray();
            $data['list'] = $students;
            unset($info['data']);
            $data['pager'] = $info;
        }else{
            $data = $students;
        }

        if(empty($students)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }
}
